<template>
	<up-notice-bar :text="text" speed="50"></up-notice-bar>
	<view class="video_auth">
		<ssection title="上传视频活体认证"></ssection>
		<up-cell title="真实姓名" :value="user.name"></up-cell>
		<up-cell title="身份证号" :value="user.idCard"></up-cell>
		<up-cell title="人脸核身">
			<template v-slot:value>
				<div style="width: 100px;">
					<up-button type="primary" color="rgb(0,129,255)" @click="uploadVedio" size="small" :disabled="next"
						:loading="uploadLoading" loadingText="正在上传">{{ next ? '认证成功' : '认证' }}</up-button>
				</div>
			</template>
		</up-cell>
		<up-button style="width: 90%;position: fixed;bottom: 20px;left: 5%;" type="primary" @click="goNext"
			:disabled="!next">下一步</up-button>
	</view>
	<up-toast ref="uToastRef"></up-toast>
</template>

<script setup>
import {
	ref,
	reactive,
	onMounted,
	nextTick
} from "vue"
import {
	onLoad,
	onShow
} from "@dcloudio/uni-app"
import ssection from '@/components/ssection.vue'
import {
	authVideo,
	openAnxinqian,
	getAnxinqianOpenStatus,
	judgeIdentify
} from '@/api/driver.js'
import {
	useUserStore
} from '@/store'
import {
	storeToRefs
} from "pinia"
import {
	getRealNameInfo
} from '@/api/user.js'
import {
	realAuth
} from '@/api/assignor.js'


/* hooks */
// 从pinia拿出token，根据token有无实现后续逻辑
const {
	role
} = storeToRefs(useUserStore())



/* 数据 */
const text = ref('人脸识别注意事项：1、人脸识别不在本小程序认证，需跳转其他小程序认证；2、人脸识别时请确保画面清晰，无遮挡，无抖动进行人脸识别；3、请确保网络稳定；4、人脸识别时请按提示进行操作。')
const uToastRef = ref(null)
// 用户信息
const user = reactive({
	name: '',
	idCard: '',
	phoneNumber: '',
	realStatus: role.value === 'driver' ? "DRIVER_REAL" : 'CAPTAIN_REAL'
})
// 下一步按钮控制
const next = ref(false)
// 上传视频按钮控制
const uploadLoading = ref(false)



/* 函数 */
// 上传视频
const uploadVedio = async () => {
	uToastRef.value.show({
		message: '正在获取您的信息',
		type: 'loading',
		duration: -1
	})
	let { data } = await getRealNameInfo({
		realStatus: role.value === 'driver' ? "DRIVER_REAL" : 'CAPTAIN_REAL'
	})
	uToastRef.value.hide()
	let flowId = data.data.flowId
	let bizToken = data.data.faceToken
	uni.navigateToMiniProgram({
		appId: 'wx1cf2708c2de46337',  // 上链公证签小程序APPID
		path: `/pages/face/index?bizToken=${bizToken}`,
		extraData: {
			requestObj: {  // 必填，入参
				flowId, // 必填，认证流程Id
				type: 'REALNAME'// 必填，业务类型：实名 REALNAME
			}
		}
	})
	return

	uni.showModal({
		title: '录制时读出1,2,3的数字顺序',
		content: '并保持5秒的时长',
		success: async (res) => {
			if (res.confirm) {
				uni.chooseVideo({
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: async (res) => {
						uToastRef.value.show({
							message: '正在准备视频',
							type: 'loading',
							duration: -1
						})
						uni.compressVideo({
							src: res.tempFilePath,
							quality: "high",
							success: async (res) => {
								if (res.size > 20 * 1024 * 1024) {
									uToastRef.value.show({
										message: '视频大小超过20MB',
										type: 'error'
									})
									return
								}
								uToastRef.value.show({
									message: '上传中',
									type: 'loading',
									duration: -1
								})
								uploadLoading.value = true
								let response = await authVideo(res.tempFilePath, user)
								uToastRef.value.hide()
								uploadLoading.value = false
								if (response.success) {
									uToastRef.value.show({
										message: '认证成功',
										type: 'success'
									})
									next.value = true
								}
							},
							fail: (err) => {
								uToastRef.value.show({
									message: '视频压缩失败' + err.errMsg || err.message || err,
									type: 'error'
								})
							}
						})


						// if (res.size > 20 * 1024 * 1024) {
						// 	uToastRef.value.show({
						// 		message: '视频大小超过20MB',
						// 		type: 'error'
						// 	})
						// 	return
						// }
						// uploadLoading.value = true
						// uToastRef.value.show({
						// 	message: '上传中',
						// 	type: 'loading',
						// 	duration: -1
						// })
						// let response = await authVideo(res.tempFilePath, user)
						// uToastRef.value.hide()
						// uploadLoading.value = false
						// if (response.success) {
						// 	uToastRef.value.show({
						// 		message: '认证成功',
						// 		type: 'success'
						// 	})
						// 	next.value = true
						// }
					}
				})
			}
		}
	})
}
const goNext = async () => {
	uToastRef.value.show({
		message: '正在获取电子签状态',
		type: 'loading',
		duration: -1
	})
	// 获取电子签状态
	let statusRes = await getAnxinqianOpenStatus()
	uToastRef.value.hide()
	if (statusRes.success) {
		if (statusRes.data) {
			// 已开通
			uToastRef.value.show({
				position: 'top',
				message: '您已开通电子签,两秒后返回',
				type: 'success',
				complete() {
					uni.navigateBack({
						delta: 2
					})
				}
			})
		} else {
			// 未开通
			uni.showModal({
				title: '提示',
				content: '是否开通电子签',
				success: async (res) => {
					if (res.confirm) {
						let {
							name,
							phoneNumber,
							idCard
						} = user
						uToastRef.value.show({
							message: '正在电子签开户',
							type: 'loading',
							duration: -1
						})
						let response = await openAnxinqian({
							name,
							phoneNumber,
							idNumber: idCard
						})
						uToastRef.value.hide()
						if (response.success) {
							uni.navigateTo({
								url: `/package_mine/pages/auth/code?delta=3`
							})
						} else {
							uToastRef.value.show({
								message: '系统错误，两秒后返回',
								type: 'error',
								position: 'top',
								complete() {
									uni.navigateBack({
										delta: 2
									})
								}
							})
						}
					}
				}
			})
		}
	}
}
// 初始化封装
const init = async () => {
	uToastRef.value.show({
		message: '加载中',
		type: 'loading',
		duration: -1
	})
	let res = await judgeIdentify()
	uToastRef.value.hide()
	if (res.success) {
		if (res.data.includes('DRIVER_REAL') || res.data.includes('CAPTAIN_REAL')) {
			uToastRef.value.show({
				message: '您已认证，两秒后返回',
				type: 'success',
				position: 'top',
				complete() {
					uni.navigateBack({
						delta: 2
					})
				}
			})
		}
	} else {
		uToastRef.value.show({
			message: '系统异常',
			type: 'error',
			position: 'top',
			complete() {
				uni.navigateBack({
					delta: 2
				})
			}
		})
	}
}


/* 钩子 */
onLoad((options) => {
	if (!options.info) {
		uni.navigateBack()
		return
	}
	let {
		name,
		idCard,
		phoneNumber
	} = JSON.parse(decodeURIComponent(options.info))
	if (!name || !idCard || !phoneNumber) {
		uni.navigateBack()
		return
	}
	Object.assign(user, {
		name,
		idCard,
		phoneNumber
	})
})
onShow(async () => {
	const options = uni.getEnterOptionsSync()
	await nextTick()
	if (options.referrerInfo.extraData.faceResult && options.referrerInfo.extraData.faceResult.ErrorCode === 0) {
		uToastRef.value.show({
			message: '认证中，请稍等',
			type: 'loading',
			duration: -1
		})
		let res = await realAuth(user)
		uToastRef.value.hide()
		if (res.success) {
			uToastRef.value.show({
				message: '认证成功',
				type: 'success',
				position: 'top'
			})
			next.value = true
		}
	}
})
onMounted(() => {
	init()
})
</script>


<style lang="scss" scoped>
.video_auth {
	padding: 10px;
	min-height: calc(100vh - 44px);
	background-color: #fff;
}
</style>